package cn.my.springHDFS.Interceptor;

import cn.my.springHDFS.domain.SpiderStatus;
import cn.my.springHDFS.repository.UserRepository;
import cn.my.springHDFS.util.HDFS_Util;
import cn.my.springHDFS.util.ToolUtil;
import org.apache.hadoop.conf.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * Created by Leo on 2017/8/7.
 * 异步任务实现类
 */
@Service
public class AsyncTaskServiceImpl {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private HDFS_Util hdfs_util;

    //通过@Async注解表明该方法是一个异步方法，如果注解在类级别，则表明该类所有的方法都是异步方法，而这里的方法自动被注入使用ThreadPoolTaskExecutor作为TaskExecutor
    @Async
    public void executeAsyncTaskTest1() {
        System.out.println("异步任务测试!");
    }

    /**
     * 异步多线程队列将用户上传到服务器本地的文件上传到HDFS，并删除在本地的文件
     * 两个参数:本地路径，HDFS上传后的路径
     * @param localFilePath
     * @param HDFS_FilePath
     */
    @Async
    public boolean uploadUserFileToHDFS(String localFilePath, String HDFS_FilePath){

        //实例化ToolUtil
        ToolUtil toolUtil = new ToolUtil();
        List<Object> objectList = toolUtil.ipSwitch(SpiderStatus.getIsActive());
        Configuration conf = (Configuration) objectList.get(0);
        boolean putToHDFS = hdfs_util.putToHDFS(localFilePath, HDFS_FilePath, conf, "");
        if (putToHDFS){
            //上传成功以后，删除本地服务器的文件，节省储存空间
            File deleteFile = new File(localFilePath);
            return deleteFile.delete();
        }
        //上传失败
        return false;
    }

    @Async
    public void addUserUploadFileHistory(String username, String uploadFilePath_HDFS){

    }
}
